package io.api.modules.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.admin.common.constant.Constant;
import io.admin.common.page.PageData;
import io.admin.common.service.impl.CrudServiceImpl;
import cn.hutool.core.util.StrUtil;
import io.api.enums.ProjectRole;
import io.api.enums.ProjectStatus;
import io.api.modules.project.dao.ProjectDao;
import io.api.modules.project.dto.ProjectDTO;
import io.api.modules.project.entity.ProjectEntity;
import io.api.modules.project.service.ProjectService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 项目表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-07-12
 */
@Service
public class ProjectServiceImpl extends CrudServiceImpl<ProjectDao, ProjectEntity, ProjectDTO> implements ProjectService {

    @Override
    public QueryWrapper<ProjectEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
//        String state  = (String)params.get("state");
//        List<Integer> intState = Arrays.stream(state.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        QueryWrapper<ProjectEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);
//        wrapper.in(!intState.isEmpty(), "state", intState);
        return wrapper;
    }

    @Override
    public PageData<ProjectDTO> page(Map<String, Object> params) {

        //转换成like
        paramsToLike(params, "projectName");

        // 设置查询项目负责人查询条件
        params.put("projectRole", ProjectRole.HEAD.getValue());

        // 转换状态
        String state  = (String)params.get("state");
        List<Integer> intState = Arrays.stream(state.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        params.put("stateList", intState);
        //分页
        IPage<ProjectEntity> page = getPage(params, Constant.CREATE_DATE, false);

        //查询
        List<ProjectEntity> list = baseDao.getList(params);
        return getPageData(list, page.getTotal(), ProjectDTO.class);
    }

    @Override
    public int countByUserIdAndStatus(Long userId, List<Integer> stateList) {
        return baseDao.countByUserIdAndStatus(userId, stateList);
    }

    @Override
    public void examine(Long projectId) {
        ProjectEntity projectEntity = baseDao.selectById(projectId);
        // 状态设置为待验收
        projectEntity.setState(ProjectStatus.EXAMINE.ordinal());
        // 审核状态设置成待验收
        projectEntity.setExamineState(1);
        baseDao.updateById(projectEntity);
    }
}